package com.spd.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spd.shop.common.Constants;
import com.spd.shop.controller.dto.AdminDTO;
import com.spd.shop.entity.Admin;
import com.spd.shop.exception.ServiceException;
import com.spd.shop.mapper.AdminMapper;
import com.spd.shop.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spd.shop.utils.TokenUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 孙沛栋
 * @since 2023-03-14
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private static final Log LOG = Log.get();

    @Override
    public AdminDTO login(AdminDTO adminDTO) {

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminDTO.getUsername());
        queryWrapper.eq("password", adminDTO.getPassword());

        Admin one;
        try {
            one = getOne(queryWrapper); //从数据库查询信息

        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (one != null){
            BeanUtil.copyProperties(one,adminDTO,true);
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            adminDTO.setToken(token);
            return adminDTO;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }
}
